package com.grt.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.grt.admin.AdminConstants;
import com.grt.admin.dao.CaseDao;
import com.grt.admin.domain.Case;
import com.grt.admin.service.CaseService;
import com.grt.admin.util.CaseQuery;
import com.grt.common.util.StringUtil;

@Service
public class CaseServiceImpl implements CaseService{

	@Autowired
	private CaseDao caseDao;

	public Case saveCase(Case oCase) {
		Case aCase = caseDao.save(oCase);
		return aCase;
	}

	/**
	 * 获取案列列表
	 * 
	 * @param pageindex
	 * @param pagesize
	 * @return
	 */
	public Page<Case> getCaseList(int pageindex, int pagesize) {
		Pageable pageable = new PageRequest(pageindex, pagesize, Sort.Direction.ASC, "id");
		Page<Case> page = caseDao.findAll(pageable);

		return page;
	}

	/**
	 * 获取首页案例列表
	 * 
	 * @return
	 */
	public List<Case> getIndexCaseList(CaseQuery caseQuery) {
		int pagesize = caseQuery.getLimit() == 0 ? AdminConstants.DEF_PAGESIZE : caseQuery.getLimit();
		Pageable pageable = new PageRequest(AdminConstants.DEF_PAGEINDEX, pagesize);
		Page<Case> page = caseDao.findAll(new Specification<Case>() {
			@Override
			public Predicate toPredicate(Root<Case> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> prList = new ArrayList<Predicate>();
				if (!StringUtil.isEmpty(caseQuery.getName())) {
					prList.add(criteriaBuilder.like(root.get("casename").as(String.class),
							"%" + caseQuery.getName() + "%"));
				}
				if (!StringUtil.isEmpty(caseQuery.getDesc())) {
					prList.add(criteriaBuilder.like(root.get("casedesc").as(String.class),
							"%" + caseQuery.getDesc() + "%"));
				}
				if (!StringUtil.isEmpty(caseQuery.getType())) {
					prList.add(criteriaBuilder.equal(root.get("type").as(String.class), caseQuery.getType()));
				}

				Predicate[] p = new Predicate[prList.size()];
				return criteriaBuilder.and(prList.toArray(p));
			}
		}, pageable);
		return page.getContent();
	}

	public Case getCaseById(long caseId) {
		Case oCase = caseDao.findOne(caseId);
		return oCase;
	}

	public void deleteCase(Case oCase) {
		caseDao.delete(oCase);
	}

}